from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin

from admin_user.models import AdminUser


class PermissionMiddleware(MiddlewareMixin):
    WHITELIST = ['/auth/version', '/api/auth/version', '/auth/login', '/api/auth/login']
    CAPTCHA_URL = '/auth/captcha'

    def __init__(self, get_response=None):
        self.get_response = get_response

    def __call__(self, request):
        if request.path in self.WHITELIST or request.path.startswith(self.CAPTCHA_URL):
            return self.get_response(request)

        if request.user.is_authenticated:
            return self.get_response(request)

        if self.check_token_permission(request):
            return self.get_response(request)

        if self.check_user_permission(request):
            return self.get_response(request)
        return JsonResponse({"error": "Unauthorized"}, status=401)

    def check_token_permission(self, request):
        token = request.META.get("HTTP_X_TOKEN")
        return token == "607f5c5a-ce8a-518e-de33-f9434bbed3b1"

    def check_user_permission(self, request):
        return not request.user.is_anonymous and request.user.admin_level in [
            AdminUser.SYSTEM_ADMIN,
            AdminUser.ACCOUNT_ADMIN,
            AdminUser.STRATEGY_ADMIN
        ]
